package com.mlxg.master.service.impl;/**
 * @author zcy
 * @date 2025/8/22 11:14
 */

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mlxg.master.domain.HzProductSeries;
import com.mlxg.master.domain.HzReviewReceive;
import com.mlxg.master.mapper.HzReviewReceiveMapper;
import com.mlxg.master.service.IHzReviewReceiveService;
import com.mlxg.selver.domain.HzProductSeriesSlave;
import com.mlxg.selver.domain.HzProductServicesIdMapping;
import com.mlxg.selver.domain.HzReviewIdMapping;
import com.mlxg.selver.domain.HzReviewSlave;
import com.mlxg.selver.domain.IdMapping;
import com.mlxg.selver.service.IHzReviewIdMappingService;
import com.mlxg.selver.service.IHzReviewSlaveService;
import com.mlxg.untils.oss.GeneralOSSUpLoadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author zcy
 * @date 2025/8/22 11:14
 * @description: old往届展会回顾
 */
@Slf4j
@Service
@DS("master")
public class HzReviewReceiveServiceImpl extends ServiceImpl<HzReviewReceiveMapper, HzReviewReceive> implements IHzReviewReceiveService {

    @Autowired
    private GeneralOSSUpLoadUtils generalOSSUpLoadUtils;
    @Autowired
    private HzReviewReceiveMapper hzReviewReceiveMapper;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private IHzReviewSlaveService hzReviewSlaveService;
    @Autowired
    private IHzReviewIdMappingService iHzReviewIdMappingService;

    /**
     * 迁移往届展会回顾
     */
    @Override
    public void transferHzReview() {
        int pageSize = 1000;
        int pageNum = 1;
        int totalProcessed = 0;
        int totalSuccess = 0;
        int totalFailed = 0;
        int totalPageFailed = 0;
        log.info("开始往届展会回顾数据迁移，每页处理 {} 条记录", pageSize);

        QueryWrapper<HzReviewReceive> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", "0");

        List<HzReviewReceive> HzReviewReceiveList = null;
        do {
            try {
                Page<HzReviewReceive> page = new Page<>(pageNum, pageSize);
                HzReviewReceiveList = hzReviewReceiveMapper.selectPage(page, queryWrapper).getRecords();

                if (CollectionUtil.isEmpty(HzReviewReceiveList)) {
                    log.info("分页查询完成，没有更多数据，共处理 {} 页", pageNum - 1);
                    break;
                }
                totalProcessed += HzReviewReceiveList.size();
                log.info("开始处理第 {} 页数据，当前页记录数: {}", pageNum, HzReviewReceiveList.size());

                int pageSuccess = 0;
                int pageFailed = 0;

                // 处理当前页的所有记录
                for (HzReviewReceive oldHzReview : HzReviewReceiveList) {
                    try {
                        processSingleRecord(oldHzReview);
                        pageSuccess++;
                        totalSuccess++;
                    } catch (Exception e) {
                        pageFailed++;
                        totalFailed++;
                        log.error("处理单条记录失败 - 数据ID: {}, 错误信息: {}",
                                oldHzReview.getId(), e.getMessage(), e);
                    }
                }
                log.info("第 {} 页数据处理完成 - 成功: {}, 失败: {}", pageNum, pageSuccess, pageFailed);
                pageNum++;

            } catch (Exception e) {
                totalPageFailed++;
                log.error("处理第 {} 页数据失败，错误信息: {}", pageNum, e.getMessage(), e);
                pageNum++; // 跳过当前页继续处理下一页
            }
        } while (HzReviewReceiveList !=null && HzReviewReceiveList.size() == pageSize);

        log.info("产品系列数据迁移完成！总处理记录数: {}, 成功: {}, 失败: {}, 失败页数: {}",
                totalProcessed, totalSuccess, totalFailed, totalPageFailed);
    }

    /**
     * 处理单条记录
     */
    public void processSingleRecord(HzReviewReceive oldHzReview) {
        HzReviewSlave newHzReviewSlave = createNewHzReview(oldHzReview);

        if (newHzReviewSlave != null) {
            // 处理数据迁移后id映射
            HzReviewIdMapping hzReviewIdMapping = new HzReviewIdMapping();
            hzReviewIdMapping.setHzReviewId(oldHzReview.getId());
            hzReviewIdMapping.setNewHzReviewId(newHzReviewSlave.getId());

            // 保存ID映射关系
            boolean mappingSaved = iHzReviewIdMappingService.save(hzReviewIdMapping);
            if (mappingSaved) {
                log.info("数据迁移成功 - 原始ID: {}, 新ID: {}",
                        oldHzReview.getId(), newHzReviewSlave.getId());
            } else {
                log.error("ID映射保存失败 - 原始ID: {}, 新ID: {}",
                        oldHzReview.getId(), newHzReviewSlave.getId());
            }
        }
    }

    /**
     * 创建新对象 HzReviewSlave
     */
    public HzReviewSlave createNewHzReview(HzReviewReceive oldHzReview) {
        HzReviewSlave hzReviewSlave = modelMapper.map(oldHzReview, HzReviewSlave.class);
        hzReviewSlave.setDelFlag(0);
        hzReviewSlave.setAuditFlag(0);

        // 处理封面图URL
        try {
            hzReviewSlave.setReviewImg(processUrlField(oldHzReview.getReviewImg(), "reviewImg"));
            hzReviewSlave.setReviewCoverImg(processUrlField(oldHzReview.getReviewCoverImg(), "reviewCoverImg"));
        } catch (IOException e) {
            log.error("处理URL字段失败，ID: {}, 错误信息: {}", oldHzReview.getId(), e.getMessage(), e);
        }

        boolean save = hzReviewSlaveService.save(hzReviewSlave);
        return save ? hzReviewSlave : null;
    }

    /**
     * 处理URL字段，将相对路径转换为OSS地址
     */
    private String processUrlField(String fieldValue, String ossDir) throws IOException {
        if (StringUtils.isBlank(fieldValue)) {
            return null;
        }

        StringBuilder urlBuilder = new StringBuilder();
        String[] parts = fieldValue.split(",");

        for (int i = 0; i < parts.length; i++) {
            String part = parts[i];
            if (part.startsWith("http://") || part.startsWith("https://")) {
                urlBuilder.append(part);
            } else {
                String url = generalOSSUpLoadUtils.uploadUrlToOss(part, ossDir);
                urlBuilder.append(url);
            }

            if (i < parts.length - 1) {
                urlBuilder.append(",");
            }
        }

        return urlBuilder.toString();
    }
}
